package com.book.lizhi.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;

import com.android.volley.VolleyError;
import com.book.lizhi.http.OnHttpAsyncListener;
import com.book.lizhi.http.OnHttpListener;

public class HttpPullRefreshLayout extends SwipeRefreshLayout implements OnHttpListener {
	private OnHttpAsyncListener onHttpAsyncListener;
	private Handler mHandler;
	private boolean isInit = false;
	private boolean isDefaultMode=true;

	public HttpPullRefreshLayout(Context context) {
		this(context, null);
	}

	public HttpPullRefreshLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		Looper looper = Looper.getMainLooper();
		mHandler = new Handler(looper);
		getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onGlobalLayout() {
				isInit = true;
				if(!isDefaultMode){
					setProgressViewEndTarget(true, (int) (getResources().getDisplayMetrics().heightPixels*(1-0.618)));
				}
				setRefreshing(true);
				getViewTreeObserver().removeGlobalOnLayoutListener(this);
			}
		});
	}

	@Override
	public void onResponse(boolean isCache,String url, String json) {
		if(!isDefaultMode){
			setProgressViewEndTarget(true, (int) (64*getResources().getDisplayMetrics().density));
		}
		mHandler.post(new Runnable() {

			@Override
			public void run() {
				setRefreshing(false);
			}
		});
		if (onHttpAsyncListener != null) {
			onHttpAsyncListener.onHttpSuccess(isCache,url, json);
		}
	}

	@Override
	public void onResponse(String response) {
	}

	@Override
	public void onErrorResponse(VolleyError error) {
		setRefreshing(false);
		if (onHttpAsyncListener != null) {
			onHttpAsyncListener.onHttpError(error);
		}
	}

	@Override
	public void onHttpStart() {

		mHandler.post(new Runnable() {

			@Override
			public void run() {
				setRefreshing(isInit);
			}
		});

	}

	public OnHttpAsyncListener getOnHttpAsyncListener() {
		return onHttpAsyncListener;
	}

	public void setOnHttpAsyncListener(OnHttpAsyncListener onHttpAsyncListener) {
		this.onHttpAsyncListener = onHttpAsyncListener;
	}

	public boolean isDefaultMode() {
		return isDefaultMode;
	}

	public void setDefaultMode(boolean isDefaultMode) {
		this.isDefaultMode = isDefaultMode;
	}

}
